package tgc.edu.tgq.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import tgc.edu.tgq.demo.custom.BaseService;
import tgc.edu.tgq.demo.entity.SysRole;
import tgc.edu.tgq.demo.entity.SysUser;
import tgc.edu.tgq.demo.repository.SysUserRepository;
import tgc.edu.tgq.demo.security.User2;

@Service
public class SysUserService extends BaseService<SysUser, Integer> implements UserDetailsService{
	@Autowired
	private SysUserRepository userDAO;
	@Autowired
	private SysRoleService roleService;
	
	public SysUser login(String username, String pwd) {
		return userDAO.findByUsernameAndPassword(username,pwd);
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user=userDAO.findByUsername(username);
		if(user==null) {
			//抛出异常UsernameNotFoundException
			throw new UsernameNotFoundException(username);
		}
		//这个方法将返回此用户的所拥有的权限。这个集合将用于用户的访问控制
		List<GrantedAuthority> authorities = new ArrayList<>();
		List<SysRole> roles = user.getRoles();
		for (SysRole role : roles) {
			//getCode角色编码，SimpleGrantedAuthority权限凭证实体类
			authorities.add(new SimpleGrantedAuthority(role.getCode()));
		}
		//返回值用户凭证
		return new User2(user.getUsername(),user.getPassword(),user.getName(),authorities);
	}

//	public static void main(String[] args) {
//		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		//判断编译过的密码和数字密码是否相同
//		String encodeCode="$2a$10$2mV/x5s.7SRujgN3/P.gQubg7KvR0ZDACn70DN/d938H4zB8VFL1O";
//		System.out.println(encoder.matches("1111", encodeCode));
		//将密码编译
//		String encodeCode=encoder.encode("1111");
//		System.out.println(encodeCode);
//	}
}
